package cn.kuang.controller;

import cn.kuang.pojo.User;
import cn.kuang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @author 徽州大都督
 * @date 2020/7/27
 */
@RestController
@RequestMapping("user")
public class UserControoler {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("login")
    public String login(@RequestBody User user){

        String code = (String) redisTemplate.opsForValue ().get ("code");

        //System.out.println (code);

        //System.out.println (user);

        if (code!=null && code.equalsIgnoreCase (user.getCode ())){
            User user1=userService.login(user);
            //System.out.println (user);
            if (user1==null){

                //用户名或密码错误
                return "error";
            }else{
                //登陆成功
                return "success";
            }
        }

        return "failer";

    }

    @PostMapping("register")
    public String register(@RequestBody User user){
        //System.out.println (user);
        String code = (String) redisTemplate.opsForValue ().get ("code");

        if (code!=null && code.equalsIgnoreCase (user.getCode ())){
            int row=userService.register (user);
            //System.out.println (user);
            if (row>0){
                //注册成功
                return "success";

            }else{
                //用户名或密码错误
                return "error";
            }
        }

        return "failer";
    }

    @GetMapping("findByUsername/{username}")
    public String findByUsername(@PathVariable("username")String username){

        int byUsername = userService.findByUsername (username);
        if (byUsername==1){
            return "error";
        }else{
            return "success";
        }
    }
}
